<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\ConsultingServer;
use app\index\service\MessageSendService;
use app\index\traits\ChatFreelyTrait;

class ConsultingQuestionNumNotEnough
{
    use ChatFreelyTrait;

    /**
     * 剩余追问次数不足 事件监听处理
     *
     * @return mixed
     */
    public function handle(Consulting $consulting)
    {
        if ($consulting->questionsNum > 0 || $this->isChatFreely($consulting)) {
            return;
        }

        // 追问次数不足

        // 不重复推送消息
        if ($consulting->questionsNumRemind == 1) {
            return;
        }
        $consulting->questionsNumRemind = 1;
        $consulting->save();

        // 查询推荐的服务
        $tableName = ConsultingServer::getTable();
        $server = ConsultingServer::leftJoin('consulting_server cs', "$tableName.id=cs.recommendServerId")
            ->where('cs.serverType', ConsultingServer::FREE)
            ->tableField(true, $tableName)
            ->find();

        if ($server) {

            // 提醒次数
            $content0 = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '剩余',],
                    ['type' => 'text', 'red' => '101', 'text' => '0次',],
                    ['type' => 'text', 'red' => '102', 'text' => '追问，如您的问题尚未解决，点击下方“立即支付”可享受' . humanized_time_length($server->chatFreelyDuration * 3600) . '不限次数畅聊，也可使用顶部电话咨询等功能。',],
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content0);

            // 推荐服务
            $content1 = [
                'id' => $server->id,
                'btnStr' => '继续咨询',
                // cancel_card 101请求取消接口 102前端拦截弹窗
                'cancel_card' => '102',
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, 0, ConsultingMessage::SERVER, $content1);

        } else {

            // 提醒次数
            $content0 = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '剩余',],
                    ['type' => 'text', 'red' => '101', 'text' => '0次',],
                    ['type' => 'text', 'red' => '102', 'text' => '追问，如您的问题尚未解决，可使用顶部电话咨询等功能。',],
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content0);
        }

    }

    private function getMessageSendService(): MessageSendService
    {
        return app(MessageSendService::class);
    }
}
